<template>
  <el-card>
      <el-form :inline="true" class="form">
          <el-form-item label="职位搜索">
              <el-input placeholder="请你输入搜索职位关键字" v-model="keyword"></el-input>
          </el-form-item>
          <el-form-item>
              <el-button type="primary" size="default" :disabled="keyword ? false : true" @click="Search">搜索</el-button>
              <el-button type="primary" size="default" @click="reset">重置</el-button>
          </el-form-item>
      </el-form>
  </el-card>
  <el-card style="margin: 10px 0px;">
      <el-button type="primary" size="default" icon="Plus" @click="addRole">添加职位</el-button>
      <el-table border style="margin: 10px 0px;" :data="allRole">
          <el-table-column type="index" align="center" label="#"></el-table-column>
          <el-table-column label="ID" align="center" prop="id"></el-table-column>
          <el-table-column label="职位名称" align="center"  prop="roleName" show-overflow-tooltip></el-table-column>
          <el-table-column label="创建世间" align="center" prop="createTime" show-overflow-tooltip ></el-table-column>
          <el-table-column label="更新时间" align="center"  prop="updateTime" show-overflow-tooltip ></el-table-column>
          <el-table-column label="操作" width="280px" align="center">
              <!-- row:已有的职位对象 -->
              <template #="{ row, $index }">
                  <el-button type="primary" size="small" icon="User" @click="setPermisstion(row)">分配权限</el-button>
                  <el-button type="primary" size="small" icon="Edit" @click="updateRole(row)">编辑</el-button>
                  <el-popconfirm :title="`你确定要删除${row.roleName}?`" width="260px" @confirm="removeRole(row.id)">
                      <template #reference>
                          <el-button type="primary" size="small" icon="Delete">删除</el-button>
                      </template>
                  </el-popconfirm>
              </template>
          </el-table-column>
      </el-table>
      <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40]"
          :background="true" layout="prev, pager, next, jumper,->,sizes,total" :total="total" @current-change="getHasRole"
          @size-change="sizeChange" />
  </el-card>
  <!-- 添加职位与更新已有职位的结构:对话框 -->
  <el-dialog v-model="dialogVisible" :title="RoleParams.id?'更新职位':'添加职位'">
      <el-form :model="RoleParams" :rules="rules" ref="form">
          <el-form-item label="职位名称" prop="roleName">
              <el-input placeholder="请你输入职位名称" v-model="RoleParams.roleName"></el-input>
          </el-form-item>
      </el-form>
      <template #footer>
          <el-button type="primary" size="default" @click="dialogVisible=false">取消</el-button>
          <el-button type="primary" size="default" @click="save" >确定</el-button>
      </template>
  </el-dialog>
  <!--分配权限  -->
  <el-drawer v-model="drawer">
    <template #header>
      <h4>分配菜单与按钮权限</h4>
    </template>
    <template #default>
     <!-- 树形控件 -->
     <el-tree ref="tree" :data="menuArr" show-checkbox node-key="id" default-expand-all
                :default-checked-keys="selectArr" :props="defaultProps" />
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="drawer = false">取消</el-button>
                <el-button type="primary" @click="handler">确定</el-button>
            </div>
        </template>
    </el-drawer>

</template>


<script setup lang="ts">
import useLayOutSettingStore from '@/store/modules/setting';
import{ ref,onMounted,reactive,nextTick} from 'vue'
import { reqAllRoleList,reqAddOrUpdateRole ,reqAllMenuList,reqRemoveRole,reqSetPermisstion} from '@/api/acl/role';
import type { RoleResponseData,Records,RoleData,MenuResponseData ,MenuList} from '@/api/acl/role/type';
import { ElMessage } from 'element-plus';
let settingStore = useLayOutSettingStore()
//当前页码
let pageNo = ref<number>(1);
//一页展示几条数据
let pageSize = ref<number>(10);
//搜索职位关键字
let keyword = ref<string>('');
//存储全部已有的职位
let allRole = ref<Records>([]);
//职位总个数
let total = ref<number>(0);
  // 对话框用v-model控制显示与隐藏
let dialogVisible = ref<boolean>(false)
//收集新增岗位数据
let RoleParams = reactive<RoleData>({
  roleName:''
})
let form = ref<any>()
let drawer = ref<boolean>()
let menuArr = ref<MenuList>([])
//准备一个数组  用于存储勾选的节点的id（四级的）
let selectArr = ref<any>([])
let tree = ref<any>()
const getHasRole = async(pager=1)=>{
  pageNo.value = pager
  let result:RoleResponseData = await reqAllRoleList(pageNo.value,pageSize.value,keyword.value)
  if(result.code==200){
    total.value = result.data.total
    allRole.value = result.data.records
  }
}

onMounted(()=>{
  getHasRole()
})
const sizeChange = ()=>{
  getHasRole()
}
const Search = ()=>{
  // 根据关键字发请求
  getHasRole()
  keyword.value = ''
}
const reset = ()=>{
  settingStore.refrsh = ! settingStore.refrsh
}
const addRole = ()=>{
  dialogVisible.value = true
  Object.assign(RoleParams,{roleName:'',id:0})
  // 点击才出来对话框  怎么清除上一次
  nextTick(()=>{
    form.value.clearValidate('roleName')
  })
}
//@ts-ignore
const updateRole = (row:RoleData)=>{
  dialogVisible.value = true
  // RoleParams.roleName=row.roleName
  Object.assign(RoleParams,row)
   // 点击才出来对话框  怎么清除上一次
   nextTick(()=>{
    form.value.clearValidate('roleName')
  })
}
//@ts-ignore
const validatorRoleName = (rule:any,value:any,callBack:any)=>{
  if(value.trim().length>=2){
    callBack()
  }else{
    callBack(new Error('职位名称至少两位'))
  }
}

const rules = {
  roleName:[{required:true,trigger:'blur',validator:validatorRoleName}]
}

const save =async ()=>{
  //必须表单校验通过  有form自带的函数
  await form.value.validate()
  let result:any = await reqAddOrUpdateRole(RoleParams)
  if(result.code==200){
    ElMessage({
      type:'success',
      message:RoleParams.id?'修改成功':'添加成功'
    })
    dialogVisible.value = false
    getHasRole(RoleParams.id?pageNo.value:1)
  }else{
    ElMessage({
      type:'error',
      message:RoleParams.id?'修改失败':'添加失败'
    })
  }
}
// row是已有职位的数据
const setPermisstion = async(row:RoleData)=>{
  drawer.value = true
  //收集数据
  Object.assign(RoleParams,row)
  let result:MenuResponseData = await reqAllMenuList((RoleParams.id as number))
  if(result.code==200){
    menuArr.value = result.data
    selectArr.value = filterSelectArr(menuArr.value,[])
  }
}

const filterSelectArr = (allData:any,initArr:any)=>{
  allData.forEach((item:any) => {
    if(item.select && item.level==4){
      initArr.push(item.id)
    }
    if(item.children && item.children.length>0){
      filterSelectArr(item.children,initArr)
    }
  });
  return initArr;
}

const defaultProps = {
  children:'children',
  label:'name'
}

//点击确定的回调
const handler = async()=>{
  //职位的id
  const roleId = (RoleParams.id as number)
  //选中节点的id
  let arr = tree.value.getCheckedKeys()
  //半选的id
  let arr1 = tree.value.getHalfCheckedKeys()
  let permissionId = arr.concat(arr1)
  let result:any = await reqSetPermisstion(roleId,permissionId)
  if (result.code == 200) {
        //抽屉关闭
        drawer.value = false;
        //提示信息
        ElMessage({ type: 'success', message: '分配权限成功' });
        //页面刷新
        window.location.reload();
    }
}

const removeRole = async(id:number)=>{
  let result:any = await reqRemoveRole(id)
  if(result.code==200){
    ElMessage({ type: 'success', message: '删除成功' });
    getHasRole(allRole.value.length>1?pageNo.value:pageNo.value-1)
  }
}
</script>

<style scoped>
.form {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 50px;
}
</style>